<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\LogService;
use Spatie\Activitylog\Models\Activity;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;

class LogController extends Controller
{
    protected $logService;

    public function __construct(LogService $logService)
    {
        $this->logService = $logService;
    }

    /**
     * 日志列表页面
     */
    public function index(Request $request): View
    {
        $query = Activity::with(['causer', 'subject'])->latest();

        // 搜索功能
        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function ($q) use ($search) {
                $q->where('description', 'like', "%{$search}%")
                  ->orWhere('event', 'like', "%{$search}%")
                  ->orWhere('log_name', 'like', "%{$search}%");
            });
        }

        // 按日志类型筛选
        if ($request->filled('log_name')) {
            $query->where('log_name', $request->input('log_name'));
        }

        // 按事件类型筛选
        if ($request->filled('event')) {
            $query->where('event', $request->input('event'));
        }

        // 按用户筛选
        if ($request->filled('user_id')) {
            $query->where('causer_id', $request->input('user_id'));
        }

        // 按日期范围筛选
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->input('date_from'));
        }

        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->input('date_to'));
        }

        $logs = $query->paginate(20);

        // 获取筛选选项
        $logNames = Activity::distinct()->pluck('log_name')->filter()->values();
        $events = Activity::distinct()->pluck('event')->filter()->values();
        $users = \App\Models\User::select('id', 'nickname')->get();

        // 获取统计信息
        $stats = $this->logService->getLogStats();

        return view('admin.logs.index', compact('logs', 'logNames', 'events', 'users', 'stats'));
    }

    /**
     * 日志详情页面
     */
    public function show(int $id): View
    {
        $log = Activity::with(['causer', 'subject'])->findOrFail($id);
        
        return view('admin.logs.show', compact('log'));
    }

    /**
     * 删除日志
     */
    public function destroy(int $id): JsonResponse
    {
        $log = Activity::findOrFail($id);
        $log->delete();

        return response()->json([
            'success' => true,
            'message' => '日志删除成功'
        ]);
    }

    /**
     * 批量删除日志
     */
    public function batchDestroy(Request $request): JsonResponse
    {
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'integer|exists:activity_log,id'
        ]);

        $deletedCount = Activity::whereIn('id', $request->input('ids'))->delete();

        return response()->json([
            'success' => true,
            'message' => "成功删除 {$deletedCount} 条日志"
        ]);
    }

    /**
     * 清理旧日志
     */
    public function cleanOldLogs(Request $request): JsonResponse
    {
        $request->validate([
            'days' => 'required|integer|min:1|max:365'
        ]);

        $deletedCount = $this->logService->cleanOldLogs($request->input('days'));

        return response()->json([
            'success' => true,
            'message' => "成功清理 {$deletedCount} 条旧日志"
        ]);
    }

    /**
     * 导出日志
     */
    public function export(Request $request): JsonResponse
    {
        $query = Activity::with(['causer', 'subject'])->latest();

        // 应用相同的筛选条件
        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function ($q) use ($search) {
                $q->where('description', 'like', "%{$search}%")
                  ->orWhere('event', 'like', "%{$search}%")
                  ->orWhere('log_name', 'like', "%{$search}%");
            });
        }

        if ($request->filled('log_name')) {
            $query->where('log_name', $request->input('log_name'));
        }

        if ($request->filled('event')) {
            $query->where('event', $request->input('event'));
        }

        if ($request->filled('user_id')) {
            $query->where('causer_id', $request->input('user_id'));
        }

        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->input('date_from'));
        }

        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->input('date_to'));
        }

        $logs = $query->limit(1000)->get();

        // 这里可以实现CSV或Excel导出
        // 暂时返回JSON格式
        return response()->json([
            'success' => true,
            'data' => $logs,
            'message' => '日志导出成功'
        ]);
    }

    /**
     * 获取日志统计图表数据
     */
    public function getChartData(Request $request): JsonResponse
    {
        $days = $request->input('days', 7);
        $startDate = now()->subDays($days);

        // 按日期统计日志数量
        $dailyStats = Activity::selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->where('created_at', '>=', $startDate)
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        // 按事件类型统计
        $eventStats = Activity::selectRaw('event, COUNT(*) as count')
            ->where('created_at', '>=', $startDate)
            ->whereNotNull('event')
            ->groupBy('event')
            ->orderBy('count', 'desc')
            ->get();

        // 按用户统计
        $userStats = Activity::selectRaw('causer_id, COUNT(*) as count')
            ->where('created_at', '>=', $startDate)
            ->whereNotNull('causer_id')
            ->with('causer:id,nickname')
            ->groupBy('causer_id')
            ->orderBy('count', 'desc')
            ->limit(10)
            ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'daily' => $dailyStats,
                'events' => $eventStats,
                'users' => $userStats
            ]
        ]);
    }
}
